import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as todoActions from '../store/actions/todo.actions'

class Main extends Component {
    constructor(props) {
        super(props)
        this.state = {}
    }
    componentDidMount() {
        this.props.load_todo()
    }
    delAction(id) {
        if (window.confirm('确定删除当前元素？')) {
            this.props.remove_todo(id)
        }
    }
    modify_todos (item, ev) {
        this.props.modify_active({id: item.id, taskName: ev.target.value})
        this.props.modify_todo_edit({id: item.id, isEditing: false})

    }
    render() {
        return (
            <section className="main">
                <input className="toggle-all" type="checkbox" />
                <ul className="todo-list">
                    {
                        this.props.todos.map(item => {
                            let classArr = []
                            if (item.isCompleted) classArr.push('completed')
                            if (item.isEditing) classArr.push('editing')
                            return (
                                <li key={item.id} className={classArr.join(' ')}>
                                    <div className="view">
                                        <input className="toggle" checked={item.isCompleted} type="checkbox" onChange={(e) => { this.props.modify_todo({ id: item.id, isCompleted: e.target.checked }) }} />
                                        <label onDoubleClick={() => {this.props.modify_todo_edit({id: item.id, isEditing: true})}} className={item.isEditing.toString()}>{item.taskName}</label>
                                        <button className="destroy" onClick={this.delAction.bind(this, item.id)}></button>
                                    </div>
                                    { item.isEditing  &&<input onBlur={(ev) => {this.modify_todos(item, ev)}} autoFocus defaultValue={item.taskName} className="edit" />}
                                </li>
                            )}
                            )
                    }
                </ul>
            </section>
        );
    }
}


function filterTodos(todos, filter) {
    switch (filter) {
        case 'all':
            return todos
        case 'active':
            return todos.filter(todo => !todo.isCompleted)
        case 'completed':
            return todos.filter(todo => todo.isCompleted)
        default:
            return todos
    }
}
const mapTodoProps = state => ({
    todos: filterTodos(state.todoReducer.todos, state.todoReducer.filter)
})

const mapTodoActions = dispatch => ({
    ...bindActionCreators(todoActions, dispatch),
})

export default connect(mapTodoProps, mapTodoActions)(Main)
